package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Booking;
import model.Reservation;
import model.RoomType;
import model.User;
import dao.impl.BookingDaoImpl;
import dao.impl.RoomDaoImpl;
import dao.impl.RoomHasBookingDaoImpl;
import dao.impl.RoomTypeDaoImpl;
import dao.impl.UserDaoImpl;
import dao.intf.BookingDao;
import dao.intf.RoomDao;
import dao.intf.RoomHasBookingDao;
import dao.intf.RoomTypeDao;
import dao.intf.UserDao;

/**
 * Servlet implementation class ViewDetailServlet
 */
@WebServlet("/ViewDetailServlet")
public class ViewDetailServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewDetailServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
			
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		if (request.getParameter("edit") != null) {
			
			RequestDispatcher rd = request.getRequestDispatcher("/modifyAvailability.jsp");
			Reservation reservation=new Reservation();//add content to obj
			HttpSession session=request.getSession();
			reservation=(Reservation)session.getAttribute("reservation");
			request.setAttribute("reservation",reservation);
			rd.forward(request, response);
		    
		} else if (request.getParameter("cancel") != null) {
			deleteBooking(request,response);
			
		}
		
		 
	}
	
	
	public void deleteBooking(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
			int numberOfUnits=0;
		//booking.getStart(request.getParameter("startDate"));
		Reservation reservation=new Reservation();//add content to obj
		HttpSession session=request.getSession();
		reservation=(Reservation)session.getAttribute("reservation");
		  String bookingId = reservation.getBooking().getId();
		  String start=new SimpleDateFormat("yyyy-MM-dd").format(reservation.getBooking().getStart());
		  String end=new SimpleDateFormat("yyyy-MM-dd").format(reservation.getBooking().getEnd());
		  String email = reservation.getUser().getEmail();
		  
		  //bookingId="8PRE-20130503-035710";
		  //start="2013-05-12";
		  //end="2013-06-15";
		  //email="mayzin.ice@gmail.com";
		  
		  String status="";
		  ArrayList error=new ArrayList();
		  int duration=0;
		  try{
			   duration=Integer.parseInt(reservation.getBooking().getDuration()+"");
			  }catch(Exception ex){}
		  UserDao userDao=new UserDaoImpl();
		  RoomDao roomDao=new RoomDaoImpl();
		  BookingDao bookingDao=new BookingDaoImpl();
		  RoomHasBookingDao roomHasBookingDao=new RoomHasBookingDaoImpl();
		  RoomTypeDao roomTypeDao=new RoomTypeDaoImpl();
		  User user= userDao.getUserByEmail(email);
		  Booking booking=new Booking();
		  booking=bookingDao.getBookingById(bookingId);
		  String roomStr=request.getParameter("roomType");
		  DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
          Date startDate=new Date();
		  final Calendar calStartDate = Calendar.getInstance();
		try {
			startDate = formatter.parse(start);
			
		         try {
		        	 calStartDate.setTime(startDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		Date endDate=new Date();
		 final Calendar calEndDate = Calendar.getInstance();
		try {
			endDate = formatter.parse(end);
			 
		         try {
		        	 calEndDate.setTime(endDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		 try{
			  numberOfUnits=Integer.parseInt(request.getParameter("numberOfUnits"));
		  }catch(Exception ex){}
		 
			 RoomType roomType= roomTypeDao.getRoomDiscount(roomStr, duration);
			 Double totalPaid=0.0;
			 Double rate=0.0;
			  String roomListString="";
			  ArrayList roomListArray=new ArrayList();
			  	  	 for(int i=0;i<numberOfUnits;i++)
					  { rate+=roomType.getRate();
					  }
			  	   RoomType roomTypeRelease=roomTypeDao.getRoomTypeById(roomStr);
					  roomTypeDao.updateNoofRooms(roomStr, roomTypeRelease.getNoOfRooms()-numberOfUnits);
			  		Double discountAmount=((rate*duration)*(Double.parseDouble(roomType.getDiscountPercent()+""))/100);totalPaid=(rate*duration)-discountAmount;
					booking.setStart(calStartDate.getTime());
					booking.setEnd(calEndDate.getTime());
					booking.setDuration(duration);
					booking.setTotalPaid(totalPaid);
					booking.setCreateDate(new Date());
					booking.setUpdateDate(new Date());
					booking.setBookingStatus("C");
					booking.setNumberofUnits(numberOfUnits+"");
					booking.setRoomType(roomType.getId());
					booking.setRoomTypeName(roomType.getName());

					int recordCount=bookingDao.updateBooking(booking);
					if(recordCount>0)
					{
						RequestDispatcher rd = request.getRequestDispatcher("/viewDetail.jsp");
						
						request.setAttribute("status","ok");
						rd.forward(request, response);
						
					}else
					{
						error.add("Cancellation is not successful");
						RequestDispatcher rd = request.getRequestDispatcher("/ViewDetail.jsp");
						request.setAttribute("status","fail");
						rd.forward(request, response);
					}
		}
	
	
}
	
